import 'dart:async';

import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';

/// The plugin class for retrieving the Android ID.
class AndroidId {
  static String? _id;
  static Completer<String?>? _completer;

  const AndroidId();

  /// The method channel used to interact with the native platform.
  static const _methodChannel = MethodChannel('android_id');

  /// Calls the native method to retrieve the Android ID.
  Future<String?> getId() async {
    if (_completer != null) return _completer!.future;
    var completer = Completer<String?>();
    _completer = completer;
    var id = _id ??= await _getAndroidId();
    completer.complete(id);
    return id;
  }

  Future<String?> _getAndroidId() async {
    var sp = await SharedPreferences.getInstance();
    var androidIdKey = 'brainco.android_id';
    var saveTimeKey = 'brainco.android_id_timestamp';
    var local = sp.getString(androidIdKey);
    var timestamp = sp.getInt(saveTimeKey) ?? 0;
    var now = DateTime.now().millisecondsSinceEpoch;
    if (local == null || now - timestamp > 72 * 3600 * 1000) {
      var id = await _methodChannel.invokeMethod<String?>('getId');
      if (id != null) {
        await sp.setInt(saveTimeKey, now);
        await sp.setString(androidIdKey, id);
      }
      return id;
    } else {
      return local;
    }
  }
}
